<?php

namespace app\admin\controller\task;

use app\common\controller\Backend;
use think\Db;

/**
 * 打款记录管理
 *
 * @icon fa fa-circle-o
 */
class RecordMoney extends Backend
{
    
    /**
     * Money模型对象
     * @var \app\common\model\record\Money
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\record\Money;
        $this->view->assign("payedList", $this->model->getPayedList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index(){
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $_where["payed"] = 1;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($_where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with('order')
                ->field('*,record_id as id')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 打款成功（type：1）
     *
     * 失败注册（type：2）remark
     * @param string $ids
     * @return string
     */
    public function remarks($ids = '')
    {
        $row = $this->model->get(['record_id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row->payed == 2){
            $this->error('改笔订单已付款');
        }
        if($this->request->isPost()){
            $params = $this->request->post();
            //halt($params);
            try {
                $data = [];
                if($params["type"]==1){
                    $data["payed"] = 2;

                }elseif($params["type"]==2){
                    $data["fail_remarks"] = $params["fail_remarks"];
                }
                //unset($params["ids"]);
                //unset($params["type"]);

                $this->model->where('record_id', $ids)->update($data);
                if($params["type"]==1){//打款成功
                    Db::name("shop_order")->where("order_id",$params["order_id"])->update(["payed"=>"2","status"=>"5"]);//订单信息修改
                    $uid = $params["uid"];
                    $openid = Db::name("wx_users")->where("uid",$uid)->value("openid");
                    $date   = date("Y-m-d",time());
                    $day    = date("H:i:s",time());
                    $flag   = $params["bank_name"]."-".$params["bank_no"]."-".$params["cash"]."元";
                    $content = [
                        $date,$day,$flag
                    ];
                    $msg = [
                        "condition"=>12,
                        "touser"=>$openid,
                        "content"=>$content
                    ];
                    $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                    $MiniMsg->sendMsg();//发送短信模板打款成功
                }
                $this->success('审核通过');
            } catch (Exception $e) {
                $this->error('审核失败');
            }
        }
        $this->view->assign("type", input("type"));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 批量打款成功
     */
    public function payed(){

        $pass = input("post.");

        $ids = [];//打款记录id
        $order_ids = [];//批量订单id

        foreach ($pass["ids"] as $k=>$v){
            $ids[] = $v["record_id"];
            $order_ids[] = $v["order_id"];
        }
        try{

        Db::name("record_money")->where("record_id","in",$ids)->update(["payed"=>2]);//p

        Db::name("order")->where("order_id","in",$ids)->update(["status"=>6,"payed"=>2]);

        }catch (\Exception $e){

            renderJson($e->getMessage(),0);

        }

        renderJson("批量打款成功",1);


    }

}
